#include <stdexcept>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include "bglTexture2D.h"

static  unsigned  createTexture(int w, int h, const void* data, GLenum type)
{
	unsigned    texId;
	glGenTextures(1, &texId);
	glBindTexture(GL_TEXTURE_2D, texId);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	glTexImage2D(GL_TEXTURE_2D, 0, type, w, h, 0, type, GL_UNSIGNED_BYTE, data);
	//glGenerateMipmap(GL_TEXTURE_2D);  //为当前绑定的纹理自动生成所有需要的多级渐远纹理
	glBindTexture(GL_TEXTURE_2D, 0);

	return  texId;
}

GLuint BGLTexture2D::createTextureFromImage(std::string imageName)
{
	unsigned  int  texId = 0;
	int width, height, nrChannels;

	stbi_set_flip_vertically_on_load(true);
	unsigned char *data = stbi_load(imageName.c_str(), &width, &height, &nrChannels, 3);

	if (data)
	{
		texId = createTexture(width, height, data, GL_RGB);
		stbi_image_free(data);
	}
	else
	{
		throw std::runtime_error("Failed to load texture");
	}
	
	return texId;
}
